import React, {useEffect, useState} from 'react';
import style from './DataStatistics.module.scss'
import * as echarts from 'echarts';
import {Radio, message} from 'antd';
import {getDataPageViewCount, StatisticalSex} from './DataStatisticsApi'

//获取前30天的日期
function getDate(index) {
    if (!index) return
    index = Number(index)
    const dateList = [];
    for (let i = 0; i < index; i++) {
        let currentDate = new Date(); // 获取当前日期
        currentDate.setDate(currentDate.getDate() - (index - i)); // 将当前日期减去30天
        let year = currentDate.getFullYear(); // 获取年份
        let month = currentDate.getMonth() + 1; // 获取月份（注意月份从0开始，需要加1）
        let day = currentDate.getDate(); // 获取日期
        // 格式化日期为字符串（例如：YYYY-MM-DD）
        let formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
        dateList.push(formattedDate)
    }
    return dateList
}

//获取前六个月
function getNearMonth() {
    let dateArr = []
    let date = new Date()
    // let year = date.getFullYear()
    date.setMonth(date.getMonth() + 1, 1) // 设置到下个月
    for (let i = 0; i < 6; i++) {
        date.setMonth(date.getMonth() - 1)//每次循环一次 月份值减1
        let m = date.getMonth() + 1
        m = m < 10 ? "0" + m : m
        dateArr.push(date.getFullYear() + "-" + m)
    }
    return dateArr
}


function DataStatistics() {
    const [size, setSize] = useState('7');
    const [myChart1, setMyChart1] = useState(null)
    const [myChart2, setMyChart2] = useState(null)
    //修改展示的时间
    const radioChange = (e) => {
        setSize(e.target.value)
    }

    //请求数据初始化折线图
    const getDataPageViewCountFun = () => {
        // 基于准备好的dom，初始化echarts实例
        let xAData = null
        if (size === '7') {
            xAData = getDate(size)
        } else if (size === '30') {
            xAData = getDate(size)
        } else {
            xAData = getNearMonth().reverse()
        }

        getDataPageViewCount(xAData).then(res => {
            if (res.code === '200') {
                drawMyChart1(xAData, res.data.pageView, res.data.commentCount)
            } else {
                message.error('访问量获取失败')

            }
        }).catch(e => {
            message.error('访问量获取失败')
        })
    }

    const getStatisticalSex = () => {
        StatisticalSex().then(res => {
            if (res.code === '200') {
                drawMyChart2(res.data[0], res.data[1], res.data[2])
            } else {
                message.error('性别比例获取失败')
            }
        }).catch(e => {
            message.error('性别比例获取失败')
        })
    }


    //渲染访问量表格
    const drawMyChart1 = (xAData, pageView, commentCount) => {
        if (myChart1) {
            const option = {
                legend: {
                    left: 'center',
                },
                xAxis: {
                    type: 'category',
                    data: xAData
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '访问量',
                        data: pageView,
                        type: 'line',

                    },
                    {
                        name: '留言量',
                        data: commentCount,
                        type: 'line',
                    }
                ]
            };
            // 绘制图表
            myChart1.setOption(option);
        }
    }
    //渲染饼图
    const drawMyChart2 = (data1, data2, data3) => {
        const option = {
            title: {
                text: '性别比例',
                left: 'center'
            },
            color: ['#3398DB', '#ee6666', '#acadaf'],
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {d}%'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '性别占比',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        {value: data1, name: '男性'},
                        {value: data2, name: '女性'},
                        {value: data3, name: '未知'},
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        myChart2.setOption(option);
    }
    useEffect(() => {
        setMyChart1(echarts.init(document.getElementById('PageView')))
        setMyChart2(echarts.init(document.getElementById('myEcharts2')))
    }, [])

    useEffect(() => {
        if (myChart1) getDataPageViewCountFun()
    }, [myChart1, size])

    useEffect(() => {
        if (myChart2) getStatisticalSex()
    }, [myChart2])

    return (
        <div style={{width: '100vw'}}>
            <div style={{
                width: '1000px',
                margin: '70px auto',
                padding: '10px'
            }}>
                <div>
                    <div className={style.FlowTrend}>
                        <h5>流量趋势</h5>
                        <Radio.Group value={size} size="small"
                                     onChange={radioChange}>
                            <Radio.Button value="7">近七天</Radio.Button>
                            <Radio.Button value="30">近一个月</Radio.Button>
                            <Radio.Button value="180">近半年</Radio.Button>
                        </Radio.Group>
                    </div>
                    <div id='PageView' style={{width: '100%', height: '500px', backgroundColor: "#fff"}}></div>
                </div>
                <div className={style.myEcharts2Container}>
                    <div id='myEcharts2' style={{width: '100%', height: '100%', backgroundColor: "#fff"}}></div>
                </div>
            </div>
        </div>
    );
}

export default DataStatistics;
